import React, { useState, useEffect } from 'react';
import { Routes, Route, useNavigate } from 'react-router-dom';
import { walletApi } from '../../services/apiService';

// DID列表组件
const DidList = () => {
  const [dids, setDids] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchDids = async () => {
      try {
        setLoading(true);
        const response = await walletApi.listDids();
        if (response.success) {
          setDids(response.dids);
        } else {
          setError('获取DID列表失败');
        }
      } catch (error) {
        console.error('获取DID列表出错:', error);
        setError('获取DID列表时发生错误，请稍后再试');
      } finally {
        setLoading(false);
      }
    };

    fetchDids();
  }, []);

  if (loading) {
    return (
      <div className="loading-spinner">
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">加载中...</span>
        </div>
      </div>
    );
  }

  return (
    <div className="did-list">
      <div className="d-flex justify-content-between align-items-center mb-4">
        <h4 className="section-title">数字身份管理</h4>
        <button
          className="btn btn-primary"
          onClick={() => navigate('/wallet/dids/create')}
        >
          <i className="bi bi-plus-circle me-2"></i>
          创建新身份
        </button>
      </div>

      {error && <div className="alert alert-danger">{error}</div>}

      {dids.length === 0 ? (
        <div className="alert alert-info">
          您还没有创建任何数字身份。点击"创建新身份"按钮开始创建。
        </div>
      ) : (
        <div className="card">
          <div className="card-body">
            <div className="table-responsive">
              <table className="table table-hover">
                <thead>
                  <tr>
                    <th>DID方法</th>
                    <th>身份标识符</th>
                    <th>创建日期</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {dids.map((did, index) => (
                    <tr key={index}>
                      <td>
                        <span className="badge bg-info">{did.method}</span>
                      </td>
                      <td className="text-truncate" style={{ maxWidth: '300px' }}>
                        <small>{did.id}</small>
                      </td>
                      <td>{new Date(did.created).toLocaleString()}</td>
                      <td>
                        <div className="btn-group btn-group-sm">
                          <button
                            className="btn btn-outline-primary"
                            onClick={() => {
                              // 复制DID到剪贴板
                              navigator.clipboard.writeText(did.id);
                              alert('DID已复制到剪贴板');
                            }}
                          >
                            <i className="bi bi-clipboard"></i>
                          </button>
                          <button className="btn btn-outline-secondary">
                            <i className="bi bi-eye"></i>
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 创建DID组件
const CreateDid = () => {
  const [methodType, setMethodType] = useState('polygonid');
  const [network, setNetwork] = useState('amoy');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [result, setResult] = useState(null);
  const navigate = useNavigate();

  const handleCreateDid = async () => {
    try {
      setLoading(true);
      setError(null);
      setResult(null);

      let response;
      if (methodType === 'polygonid') {
        response = await walletApi.createPolygonId();
      } else if (methodType === 'ethr') {
        response = await walletApi.createEthrId(network);
      }

      if (response.success) {
        setResult(response.did);
      } else {
        setError(response.error || '创建DID失败');
      }
    } catch (error) {
      console.error('创建DID出错:', error);
      setError('创建DID时发生错误，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="create-did">
      <div className="d-flex justify-content-between align-items-center mb-4">
        <h4 className="section-title">创建新身份</h4>
        <button
          className="btn btn-outline-secondary"
          onClick={() => navigate('/wallet/dids')}
        >
          <i className="bi bi-arrow-left me-2"></i>
          返回列表
        </button>
      </div>

      <div className="card mb-4">
        <div className="card-body">
          <form>
            <div className="mb-3">
              <label className="form-label">DID方法</label>
              <div className="form-check">
                <input
                  className="form-check-input"
                  type="radio"
                  name="didMethod"
                  id="methodPolygonId"
                  value="polygonid"
                  checked={methodType === 'polygonid'}
                  onChange={() => setMethodType('polygonid')}
                />
                <label className="form-check-label" htmlFor="methodPolygonId">
                  Polygon ID (did:polygonid)
                </label>
              </div>
              <div className="form-check">
                <input
                  className="form-check-input"
                  type="radio"
                  name="didMethod"
                  id="methodEthr"
                  value="ethr"
                  checked={methodType === 'ethr'}
                  onChange={() => setMethodType('ethr')}
                />
                <label className="form-check-label" htmlFor="methodEthr">
                  Ethereum (did:ethr)
                </label>
              </div>
            </div>

            {methodType === 'ethr' && (
              <div className="mb-3">
                <label htmlFor="ethrNetwork" className="form-label">
                  网络
                </label>
                <select
                  className="form-select"
                  id="ethrNetwork"
                  value={network}
                  onChange={(e) => setNetwork(e.target.value)}
                >
                  <option value="amoy">Polygon Amoy (测试网)</option>
                  <option value="mainnet">Polygon Mainnet</option>
                  <option value="mumbai">Polygon Mumbai</option>
                  <option value="goerli">Ethereum Goerli</option>
                </select>
              </div>
            )}

            <div className="d-grid gap-2">
              <button
                type="button"
                className="btn btn-primary"
                onClick={handleCreateDid}
                disabled={loading}
              >
                {loading ? (
                  <>
                    <span className="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                    创建中...
                  </>
                ) : (
                  <>
                    <i className="bi bi-plus-circle me-2"></i>
                    创建身份
                  </>
                )}
              </button>
            </div>
          </form>
        </div>
      </div>

      {error && <div className="alert alert-danger">{error}</div>}

      {result && (
        <div className="card">
          <div className="card-header bg-success text-white">
            <i className="bi bi-check-circle me-2"></i>
            身份创建成功
          </div>
          <div className="card-body">
            <h5 className="card-title">身份详情</h5>
            <div className="mb-3">
              <label className="form-label">DID方法:</label>
              <div className="form-control bg-light">{result.method}</div>
            </div>
            <div className="mb-3">
              <label className="form-label">身份标识符 (DID):</label>
              <div className="input-group">
                <input
                  type="text"
                  className="form-control bg-light"
                  value={result.id}
                  readOnly
                />
                <button
                  className="btn btn-outline-secondary"
                  type="button"
                  onClick={() => {
                    navigator.clipboard.writeText(result.id);
                    alert('DID已复制到剪贴板');
                  }}
                >
                  <i className="bi bi-clipboard"></i>
                </button>
              </div>
            </div>
            <div className="mb-3">
              <label className="form-label">创建日期:</label>
              <div className="form-control bg-light">
                {new Date(result.created).toLocaleString()}
              </div>
            </div>

            <div className="d-flex justify-content-between mt-4">
              <button
                className="btn btn-outline-primary"
                onClick={() => navigate('/wallet/dids')}
              >
                返回DID列表
              </button>
              <button
                className="btn btn-primary"
                onClick={() => setResult(null)}
              >
                创建另一个DID
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// 主DID管理组件
const DidManager = () => {
  return (
    <Routes>
      <Route path="/" element={<DidList />} />
      <Route path="/create" element={<CreateDid />} />
    </Routes>
  );
};

export default DidManager; 